import { Component } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';

declare var form: any;
declare var base: any;
declare var security: any;

@Component({
  templateUrl: './tenant.user.component.html'
})
export class TenantUserComponent {

  fs: any = null;
  adminDic: any = null;
  typeDic: any = null;

  constructor(private msg: NzMessageService, private http: HttpClient) {
    this.fs = new form.FormSimpleService('tenantuser', {
      orderObject: { id: 0 },
      keyField: 'id',
      randomFields: ['id']
    });
    this.fs.loadData(true);

    // 初始化字典
    this.adminDic = new form.DictionaryService('p_administrative');
    this.typeDic = new form.DictionaryService('p_company_type');
  }

  initTenantUser(data) {
    const datas = this.setTenantData(data);
    datas.subscribe(
      () => {
        this.msg.success('初始化成功！');
      },
      () => {
        this.msg.success('初始化失败，请联系管理员！');
      }
    );
  }

  // 设置租户初始化数据
  setTenantData(datas): Observable<any[]> {
    const url = base.BaseService.getHostUrl() + '/tenantuser/initTenantData';
    const jwts = security.SecurityService.jwt;
    return this.http.post<any[]>(url, datas, { headers: new HttpHeaders({ jwt: jwts }) })
      .pipe(retry(1), catchError(this.handleError));
  }

  private handleError(error: HttpErrorResponse) {
    return throwError('数据请求失败，稍后请重试！');
  }
}
